package com.bawei.newsapplication.view.adapter

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
/**
 * @author : 谢庆平
 * @date   : 2024/10/22 9:03
 * @desc   :
 */
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

    companion object {
        private const val DATABASE_NAME = "my_database.db"
        private const val DATABASE_VERSION = 1

        // 定义表名和列名
        const val TABLE_NAME = "my_table"
        const val COLUMN_ID = "id"
        const val COLUMN_NAME = "name"
        const val COLUMN_AGE = "age"
    }

    override fun onCreate(db: SQLiteDatabase) {
        // 创建表的SQL语句
        val createTableQuery = "CREATE TABLE $TABLE_NAME ($COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, $COLUMN_NAME TEXT)"
        db.execSQL(createTableQuery)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // 如果数据库版本升级，可以在这里执行更新表结构的操作
        // 例如，如果需要添加新列，可以使用ALTER TABLE语句
        if (newVersion > oldVersion) {
            // 这里只是一个简单示例，如果需要更复杂的升级逻辑，可以根据具体情况编写
            db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
            onCreate(db)
        }
    }

    // 插入数据的方法
    fun insertData(name: String): Long {
        val db = this.writableDatabase
        val contentValues = ContentValues()
        contentValues.put(COLUMN_NAME, name)
        val rowId = db.insert(TABLE_NAME, null, contentValues)
        db.close()
        return rowId
    }

    // 查询数据的方法
    fun queryData(): ArrayList<String> {
        val dataList = ArrayList<String>()
        val db = this.readableDatabase
        val cursor = db.query(TABLE_NAME, null, null, null, null, null, null)
        if (cursor.moveToFirst()) {
            do {
                val dataMap = HashMap<String, Any>()
                var name = cursor.getString(1)
                dataList.add(name)
            } while (cursor.moveToNext())
        }
        cursor.close()
        db.close()
        return dataList
    }

    // 更新数据的方法
    fun updateData(id: Int, name: String, age: Int): Int {
        val db = this.writableDatabase
        val contentValues = ContentValues()
        contentValues.put(COLUMN_NAME, name)
        contentValues.put(COLUMN_AGE, age)
        val rowsAffected = db.update(TABLE_NAME, contentValues, "$COLUMN_ID =?", arrayOf(id.toString()))
        db.close()
        return rowsAffected
    }

    // 删除数据的方法
    fun deleteData(id: Int): Int {
        val db = this.writableDatabase
        val rowsAffected = db.delete(TABLE_NAME, "$COLUMN_ID =?", arrayOf(id.toString()))
        db.close()
        return rowsAffected
    }
    fun cleardata(){
        val db = this.writableDatabase
        db.execSQL("delete from $TABLE_NAME")
        db.close()

    }
}